package com.fengmi.configuration.security;

import com.fengmi.exception.MyAccessDenied;
import com.fengmi.filter.security.MyBasicAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * Author: 施俊豪
 * Date: 2022/2/6 0:06
 * Note: SpringSecurity配置类
 */
@Configuration
//开关注解
@EnableWebSecurity
//开启注解支持
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true,jsr250Enabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyAccessDenied myAccessDenied;

    // 静态资源放行
    @Override
    public void configure(WebSecurity web) throws Exception {
        // ignoring : 忽略
        web.ignoring().mvcMatchers("/swagger-ui.html/**","/css/**","/images/**","/plugins/**","/webjars/**",
                "/swagger-resources/**","/v2/**");

    }

    // 配置http的访问规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // antMatchers : 配置
        // 除了登录请求不需要登录，其他资源必须要登录
        http.authorizeRequests()
                //登录请求和校验请求必须放行
                .antMatchers("/user/login","/user/verify")
                .permitAll()
                // 除了以上资源，剩下的http资源都是必须登录后才能访问
                .anyRequest()
                .authenticated();

//        // 配置自定义的登录界面
//        http.formLogin()//开启表单功能
//                .loginPage("/toLogin")//定义登录界面
//                .loginProcessingUrl("/login")//自定义登录处理的url,默认是/login
//                .defaultSuccessUrl("/index",true)//登录成功跳转到index.html页面
//                .failureForwardUrl("/toLogin")//失败跳转
//        ;

        // 关闭 csrf
        http.csrf().disable();

        // 配置自定义的过滤器
        http.addFilter(new MyBasicAuthenticationFilter(authenticationManager()));

        // 自定义403的异常处理
        http.exceptionHandling().accessDeniedHandler(myAccessDenied);

        // 解决跨域问题
        http.cors();

        //解决 in a frame because it set 'X-Frame-Options' to 'DENY'问题
        http.headers().frameOptions().disable();
    }
}